/**
 * Created by liuhao  on 2016/11/7.
 */


app.controller('devSelectController', ['$rootScope', '$scope', '$filter', 'httpService', 'wtmapService', function($rootScope, $scope, $filter, httpService, wtmapService){


    $scope.featurefayers = [];
    $scope.currentDrowTool = null;
    /*
     地图初始化
     */
    $scope.mapselectIntialed = function(){

        var promise = wtmapService.intialMap('devMapselect', false, 0, $rootScope.arcgisConfig.lods); //同步调用，获取承诺接口
        promise.then(function(mapobj){

            $scope.mapcadObj = mapobj;
            $scope.mapcadObj.addDynamicMap($rootScope.arcgisConfig.baseMap);


            $scope.mapcadObj.zoomTobyXY(84307.451, 145762.144, 0);

            $scope.drawlTool = mapobj.drawApi.startDrawTool($scope.addGraphic);

        }, function(data){
            //调用承诺接口reject();
        });
    }


    /*
     地图添加图形
     */
    $scope.addGraphic = function(evt){

        $scope.mapcadObj.drawApi.clearGraphics();
        $scope.currentDrowTool = evt.geometry.type;

        if(evt.geometry.type === "point" || evt.geometry.type === "multipoint"){
            $scope.mapcadObj.drawApi.drawPoint(evt.geometry.x, evt.geometry.y);
        } else if(evt.geometry.type === "line" || evt.geometry.type === "polyline"){
            $scope.mapcadObj.drawApi.drawLine(evt.geometry.rings[0]);
        }
        else {
            $scope.mapcadObj.drawApi.drawPolygon(evt.geometry.rings[0]);
        }

        //查询
        angular.forEach($scope.featurefayers, function(layer, index){
            if(layer.visible)
            {
                var query = new esri.tasks.Query();
                query.geometry = evt.geometry;
                layer.queryFeatures(query,function(data){
                    $scope.queryResult(data, layer.name);
                }  );

            }


        });

    };

    /*
     图形查询结果
     */
    $scope.queryResult = function(result, layername){


        var features = result.features;
        if(features.length > 0){
            angular.forEach(result.features, function(e, index){

                var dataid = e.attributes.objectid;
                var rowid = layername + "_" + dataid;
                var feature = $filter('filter')($scope.resultdatas, {type : layername, pointid : dataid});

                if(feature && feature.length > 0) //已存在
                {
                    if($scope.currentDrowTool == "point" || $scope.currentDrowTool == "multipoint")
                        $('#' + rowid).trigger("click");
                }
                else //不存在
                {
                    var optionData = {layerid : "devlyr", "attributes" : {type : layername, oid : dataid}};
                    $scope.mapcadObj.drawApi.drawPoint(e.geometry.x, e.geometry.y, optionData);
                    $scope.resultdatas.push({
                        type : layername,
                        code : e.attributes.code,
                        rowid : rowid,
                        addr : e.attributes.addr,
                        pointid : dataid,
                        x : e.geometry.x,
                        y : e.geometry.y,
                        attributes : e.attributes
                    });
                }

                $scope.$apply();

            });

        }


    };

    $scope.rowclick = function(x, y){
        $scope.mapcadObj.drawApi.clearGraphics("centerlyr");
        $scope.mapcadObj.drawApi.drawPoint(x, y, {layerid : "centerlyr", symbolUrl : "assets/img/gps_location.png"});
        $scope.mapcadObj.zoomTobyXY(x, y, 0);
    };


    $scope.rowDelete = function rowDelete(evt, $event){
        var keyid = evt.item.rowid;
        var layer = $scope.mapcadObj.appMap.getLayer("devlyr");
        layer.graphics.forEach(function(e){

            if(keyid == e.attributes.type + "_" + e.attributes.oid){
                layer.remove(e);

                angular.forEach($scope.resultdatas, function(item, index){
                    // index是索引值（即下标）   item是每次遍历得到的值；
                    if(item && item.pointid == e.attributes.oid && item.type == e.attributes.type){
                        $scope.resultdatas.splice(index, 1); //移除
                    }
                });

            }

        });


    };

    /*
     加载图层
     */
    $scope.loadLayers = function loadLayers(){

        $scope.pointlayers.forEach(function(dataItem){

            if(!dataItem.isDraw){
                var featurefayer = $scope.mapcadObj.addFeatureLayer(dataItem.layerName, {
                    maxScale : 0,
                    minScale : 0,
                    definitionExpression : dataItem.layerFilter
                });

                featurefayer.setVisibility(dataItem.visibility);

                $scope.featurefayers.push(featurefayer);

                if(dataItem.selectedDatas && dataItem.selectedDatas.length > 0){
                    var strIds = "";
                    dataItem.selectedDatas.forEach(function(id){
                        strIds += "'" + id + "'" + ',';
                    });
                    strIds = strIds.substring(0, strIds.length - 1);
                    //查询图形坐标
                    $scope.mapcadObj.getFeatureByWhere(dataItem.layerName, "id in(" + strIds + ")", function(data){
                        $scope.queryResult({features : data.features}, dataItem.layerName);
                    });
                }
            }
            else {

                var layerid = "lyr" + dataItem.lyrServerid;
                httpService.request("GET", dataItem.requestUrl, null, function(result){

                    angular.forEach(result.data, function(data, index){

                        if(dataItem.uniqueValues){
                            var randervalue = data[dataItem.uniqueValues.valueField];
                            var renderInfo = $filter('filter')(dataitem.renderInfos, {'value' : randervalue});

                            if(renderInfo){
                                var ointOption = {
                                    "layerid" : layerid,
                                    "symbolUrl" : renderInfo.symbolUrl
                                };
                                $scope.mapcadObj.drawApi.drawPoint(data.Lng, data.Lat, ointOption);
                            }

                        }

                    });
                });


            }
        });


        /*var user = Application.getUser();
         if (user)
         globalMap.zoomTobyXY(JSON.parse(user.Unit.ext).goX, JSON.parse(user.Unit.ext).goY, 14);*/

    }

    /*
     工具按钮点击事件
     */
    $scope.toolclick = function(evt){
        //更换图标
        $scope.toolbtItems.forEach(function(e){
            e.imgName = e.imgName.replace("N", "D"); //更换图标为选择状态
        });
        evt.item.imgName = evt.item.imgName.replace("D", "N");

        //工具按钮画图
        if(evt.item.itemName === "clear"){
            $scope.mapcadObj.drawApi.clearGraphics();
            $scope.mapcadObj.drawApi.clearGraphics("devlyr");
            $scope.mapcadObj.drawApi.clearGraphics("centerlyr");
            $scope.resultdatas = [];
            //$("#dtlist  tr:not(:first)").empty(""); //清空表格除表头外的行

            $scope.drawlTool.deactivate();
            $scope.mapcadObj.appMap.enableMapNavigation();
        }
        else {

            var tool = evt.item.itemName.toLowerCase();
            $scope.drawlTool.activate(tool);
        }

    }

    /*
     图层开关
     */
    $scope.layerchecked = function(evt, $event){

        var layers = $filter('filter')($scope.featurefayers, {'id' : evt.item.lyrServerid});
        if(layers && layers.length > 0)
            layers[0].setVisibility($event.target.checked);

    }

}]);
app.directive('wtmapPointselect', function(){

    var tempHtml = [" <div class=\"panel\">",

        "                <div class=\"panel panel-default\">",

        "                    <div class=\"searchBox\" >",
        "                        <div class=\"input-group\">",
        "                            <input class=\"form-control input-md\" id=\"btn-input\" type=\"text\" placeholder=\"输入查询关键词\">",
        "                            <span class=\"input-group-btn\">",
        "                        <button class=\"btn btn-md\" id=\"btn-search\"><span class=\"glyphicon glyphicon-search\"></span></button>",
        "                       </span>",
        "                        </div>",
        "                    </div>",

        "                    <div class=\"panel-body\" style=\"height: 200px; overflow-y: auto;\">",
        "<table class=\"table table-hover\">",
        "    <thead class=\"bordered-darkazure\">",
        "        <tr>",
        "            <th>",
        "                选择类型",
        "            </th>",
        "            <th>",
        "                类型编码",
        "            </th>",
        "            <th>",
        "                地址",
        "            </th>",
        "            <th>",
        "                操作",
        "            </th>",
        "        </tr>",
        "    </thead>",
        "    <tbody>",
        "        <tr ng-click=\'rowclick(item.x,item.y)\' ng-repeat=\"item in resultdatas track by $index\">",
        "            <td ng-bind=\'item.type\'></td>",
        "            <td ng-bind=\'item.code\'></td>",
        "            <td ng-bind=\'item.addr\'></td>",
        "            <td> <a  ng-click=\'rowDelete(this,$event)\' id=\'{{ item.rowid }}\' class=\'trash\'  title=\'删除\'><span class=\'glyphicon glyphicon-trash\'></span></a> </td>",
        "        </tr>",
        "    </tbody>",
        "</table>",
        "                    </div>",
        "                </div>",
        "                <div class=\"panel panel-default\">",
        "                    <wt-map mapid=\"devMapselect\" height=\"400\" showgdmap=\"false\" map-intialed=\"mapselectIntialed()\"></wt-map>",
        "                    <div id=\"toolbar\"> <li ng-repeat='item in toolbtItems track by $index' > <img ng-click='toolclick(this)' id='{{ item.itemNme }}' style='position:absolute; left:{{ item.leftindex }}px; top:280px;  z-index:2; cursor: pointer;' title='{{ item.title }}'  class='btn btn-warning'   ng-src='/assets/img/Query/{{ item.imgName }}' />  </li>   </div>",
        "                    <button type=\"button\" style=\"position: absolute; left: 10px; bottom: 20px; z-index: 55;\" class=\"btn btn-primary \" data-toggle=\"collapse\" data-target=\"#info\">",
        "                        <span class=\"glyphicon glyphicon-expand\"/></button>",
        "                    <div id=\"info\" style=\"position: absolute; left: 10px; bottom: 30px; z-index: 51;\" class=\"collapse\">",
        "                        <div class=\"panel-group\" id=\"accordion\" style=\"width: 150px\"/>",
        "                        <div id=\"itemInfo\" class=\"panel panel-default\">",
        "                           <div ng-repeat='item in pointlayers track by $index' class='list-group-item active'>",
        "                              <h4 class='panel-title'><label><input ng-click='layerchecked(this,$event)' ng-checked='{{ item.visibility }}'  type='checkbox' /> <span class='text'>{{ item.layerName }}</span> </label></h4>",
        "                           </div>",
        "                        </div>",
        "                    </div>",
        "                </div>",
        "            </div>"].join("");

    var ctrl = {
        restrict : 'EA',
        replace : true,
        template : tempHtml,
        scope : {
            pointlayers : '=',
            toolbtItems : '=toolitems',
            initialayer : '=',
            resultdatas : '='
        },
        require : 'wtmapPointselect', //引入控制器时需要
        controller : 'devSelectController',
        link : function(scope, element, attrs, controller){ //控件内部一系列操作实现

            if(scope.toolbtItems.length > 0)
                scope.toolbtItems.push({itemName : "clear", title : "清除所选和选择工具", imgName : "N_删除设备.png"});


            var leftindex = 55;
            scope.toolbtItems.forEach(function(e){
                e.leftindex = leftindex;
                leftindex += 34;
            });

            scope.resultdatas = [];
            scope.$watch('initialayer', function(newvalue, oldvalue){
                if(newvalue){
                    scope.loadLayers();
                }

            });


        }
    };

    return ctrl;
});